In [30]:
#create an empty list
empty_list=[]
empty_list=list()
simpsons = ['homer', 'marge', 'bart']
In [31]:
simpsons[0]
Out[31]:
In [32]:
len(simpsons)
Out[32]:
In [33]:
# counts the number of instances
simpsons.count('bart')
Out[33]:
In [34]:
# returns index of the first reference
simpsons.index('marge')
Out[34]:
In [35]:
#append to end
simpsons.append('lisa')
simpsons
Out[35]:
In [36]:
#append multiple elments to end
simpsons.extend(['itchy','scratchy'])
simpsons
Out[36]:
In [37]:
#insert at index (shifts all elements to the right)
simpsons.insert(0, 'maggie')
simpsons
Out[37]:
In [38]:
#remove element 0 and return it
simpsons.pop(0)
Out[38]:
In [39]:
#remove element at 0 (does not return it)
del simpsons[0]
simpsons
Out[39]:
In [40]:
#search for first instance and remove it
simpsons.remove('bart')
simpsons
Out[40]:
In [41]:
#replace elmeent
simpsons[0]='krusty'
simpsons
Out[41]:
In [42]:
#conctonate lists (slower then 'extend' method)
neighbors = simpsons + ['ned','rod','todd']
neighbors
Out[42]:
Setwise list manipulations:
In [43]:
neighbors * 2
Out[43]:
Sort a list in place (modifies but does not return the list):
In [44]:
simpsons.sort()
simpsons
Out[44]:
In [45]:
#reverse sort
simpsons.sort(reverse=True)
simpsons
Out[45]:
In [46]:
#sort by a key
simpsons.sort(key=len)
simpsons
Out[46]:
Return a sorted list (does not modify the original list):
In [47]:
sorted(simpsons)
Out[47]:
In [48]:
sorted(simpsons, reverse=True, key=len)
Out[48]:
Insert into an already sorted list, and keep it sorted:
In [49]:
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)
num
Out[49]:
In [50]:
new_num = num[:]
new_num=list(num)
new_num
Out[50]:
In [51]:
# Identity compare: are they referencing the same object?
num is new_num
Out[51]:
In [52]:
# Equality compare: do they have the same data?
num == new_num
Out[52]:
In [2]:
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
[n for n in mylist if n > 0]
Out[2]:
In [3]:
[n for n in mylist if n < 0]
[-5, -7, -1]
Out[3]:
In [4]:
import math
[math.sqrt(n) for n in mylist if n > 0]
Out[4]:
In [5]:
#clip negative values
[n if n > 0 else 0 for n in mylist]
Out[5]:
In [5]:
# nested loops flattened into one list
alphas = 'abc'
digits = '123'
correct = ['a1', 'a2','a3','b1','b2','b3','c1','c2','c3']
answer = [alpha+digit for alpha in alphas for digit in digits]
answer == correct
Out[5]: